<template>
    <div class="app-container" style="padding: 0px 20px 20px 20px;">
        <el-row :gutter="10" style="margin-bottom: 9px;">
            <el-col :span="1.5">
                <el-button v-if="optBtn" type="primary" plain icon="el-icon-plus" size="mini"
                    @click="handleAdd">新增</el-button>
            </el-col>
        </el-row>
        <template v-for="list in recordsList">
            <el-descriptions :column="3" style="box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);margin-bottom: 8px;"
                v-if="recordsList.length != 0" size="small">
              <el-descriptions-item label="跟进时间：" style="margin-left:5px;">{{ list.followDateTime}}</el-descriptions-item>
                <el-descriptions-item label="跟进人：">{{ list.followPerson }}</el-descriptions-item>
                <el-descriptions-item label="审核人：">{{list.strNickName}}</el-descriptions-item>
                <el-descriptions-item label="跟进阶段：">{{ formatterFollowStage(list.followStage) }}</el-descriptions-item>
                <el-descriptions-item label="最新进展：" style="margin-left:5px;">{{ list.latestDevelopments
                    }}</el-descriptions-item>
                <el-descriptions-item label="附件:">
                    <file-view :type="showInfo" :businessId="list.recordsId" :businessCode="businessRecords"
                        @change="getFile"></file-view>
                </el-descriptions-item>
                <el-descriptions-item label="批注人：">
                    <div v-if="list.list && list.list.length > 0">
                        <div v-for="(item, index) in list.list" :key="index">
                           {{ item.annotaterName }}
                        </div>
                    </div>
                    <div v-else>{{ list.annotationsName }}</div>
                </el-descriptions-item>
                <el-descriptions-item label="批注：" style="margin-left:5px;">
                    <div v-if="list.list && list.list.length > 0">
                        <div v-for="(item, index) in list.list" :key="index">
                            {{ item.annotaterDetail }}
                        </div>
                    </div>
                    <div v-else>{{ list.annotations }}</div>
                </el-descriptions-item>
                <el-descriptions-item style="margin-left:5px;">
                    <el-button size="mini" type="text" icon="el-icon-edit" style="margin: 0px 0px 10px 260px;"
                        @click="handleUpdate(list)"
                        v-if='list.followPerson == userName' title="编辑"></el-button>
                  <el-button size="mini" type="text" icon="el-icon-s-operation" style="margin-left: 10px;" @click="handleAnnotations(list)" v-if='list.annotationsUserId && list.annotationsUserId.split(",").includes(String(userId))' title="批注"></el-button>
                  <el-button  v-if="list.businessStatus =='2' && list.followStage =='0' && userId == list.businessStatusUser" size="mini" type="text" icon="el-icon-orange" style="margin-left: 10px;" @click="handleExamine(list)" title="审核"></el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" style="margin-left: 10px;"
                        @click="handleDelete(list.recordsId)"
                        v-if='(list.annotations == null || list.annotations == "") && (userName == list.followPerson) && list.isDelete!=1' title="删除"></el-button>
                </el-descriptions-item>
                <el-descriptions-item label="附件：" style="margin-left:5px;">
                    <file-view :type="showInfo" :businessId="list.recordsId" :businessCode="businessAnnotations"
                        @change="getFile"></file-view>
                </el-descriptions-item>
            </el-descriptions>
        </template>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />
        <div class="el-table__empty-block" style="width: 1170px; height: 100%;" v-if="recordsList.length == 0">
            <span class="el-table__empty-text" style="font-size: 16px;">暂无数据</span>
        </div>
        <!-- 添加或修改【请填写功能名称】对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
              <el-row>
                <el-col :span="8">
                  <el-form-item label="时间" prop="followTime" style="width: 280px;">
                    <el-input v-model="form.followTime" disabled="disabled" />
                  </el-form-item>
                </el-col>
                <el-col :span="16">
                  <el-form-item label="跟进阶段" prop="followStage" label-width="170px">
                    <el-select v-model="form.followStage" placeholder="请选择跟进阶段" style="width: 270px;" :disabled="disabled">
                      <el-option v-for="dict in dict.type.tracking_stage" :key="dict.value" :label="dict.label"
                                 :value="dict.value"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="跟进时间" prop="followDateTime" style="width: 280px;">
                    <el-date-picker
                      v-model="form.followDateTime"
                      type="datetime"
                      placeholder="请选择跟进时间"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      :disabled="disabled"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="16">
                  <el-form-item label="跟进人" prop="followPerson" label-width="170px">
                    <el-input v-model="form.followPerson" disabled="disabled" />
                  </el-form-item>
                </el-col>
              </el-row>
                <el-form-item label="最新进展" prop="latestDevelopments" style="margin-bottom: 20px;">
                    <el-input v-model="form.latestDevelopments" type="textarea" placeholder="请输入内容" :rows="4"
                        :min-height="192" :disabled="disabled" maxlength="500" />
                </el-form-item>

                  <el-form-item
                    label="批注人"
                    prop="annotationNickName"
                    label-width="80px"
                  >
                    <el-input
                      v-model="strManagerDisplay"
                      placeholder="请选择批注人"
                      @focus="userShow(5)"
                      :readonly="readonly"
                      :disabled="disabled"
                    />
                  </el-form-item>
              <el-form-item
                label="审核人"
                prop="strNickName"
                label-width="80px"
                v-if=" form.followStage == 0"
              >
                <el-input
                  v-model="strExamineDisplay"
                  placeholder="请选择审核人"
                  @focus="userShow(6)"
                  :readonly="readonly"
                  :disabled="disabled || businessStatus =='0' || businessStatus =='1'"
                />
              </el-form-item>
                <el-form-item label="附件">
                    <file-view :key="refreshKey" :type="fileType" :businessId="cordId" :businessCode="businessRecords"
                        @change="getFile"></file-view>
                </el-form-item>
                <el-form-item label="批注" prop="annotations" v-if="isShow">
                    <el-input v-model="form.annotations" type="textarea" placeholder="请输入内容" :rows="3" :min-height="192"
                        maxlength="500" />
                </el-form-item>
                <el-form-item label="批注附件" v-if="isShow">
                    <file-view :key="refreshKey" :type="fileType2" :businessId="cordId"
                        :businessCode="businessAnnotations" @change="getFile"></file-view>
                </el-form-item>
              <el-form-item label="审核选择" prop="businessStatus" v-if="isExamine && form.followStage == 0 && businessStatus =='2'">
                <el-radio-group v-model="form.businessStatus">
                  <el-radio :label="1">审核通过</el-radio>
                  <el-radio :label="0">审核不通过</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="examine" v-if="isExamine">审 核</el-button>
              <el-button type="primary" @click="submitRemark" v-if="title =='批注跟进记录'">批 注</el-button>
                <el-button type="primary" @click="submitForm" v-if="!isExamine && title !='批注跟进记录'">确 定</el-button>
                <el-button @click="cancel">关 闭</el-button>
            </div>
        </el-dialog>

        <el-dialog :visible.sync="dialogVisible" append-to-body>
            <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
        <select-user
          ref="select"
          :type="userType"
          :sign="sign"
          :userId="selectedUserId"
          @ok="selectUser"
        ></select-user>
    </div>

</template>

<script>
import { listRecords, getRecords, delRecords, addRecords, updateRecords,commentRecords } from "@/api/enterprise/businessrecords";
import FileView from "@/components/FileView/index"
import SelectUser from "../system/role/selectUser.vue";
import {updateInformation,getInformation} from "@/api/enterprise/information";
export default {
    name: "Records",
    components: { FileView,SelectUser },
    dicts: ['tracking_stage', 'enterprise_records'],
    props: {
        bId: {
            type: String,
            default: ""
        },
        optBtn: {
            type: Boolean,
            default: true
        },
        obj: {
            type: Object,
            default: null
        },
      businessStatus:{
         type:Number,
         default:null
      },
      strNickName:{
        type:String,
        default:null
      }
    },
    data() {
        return {
            readonly: true,
            userName: "",
            userType: "0",
            sign: "1",
            fileType: 0,
            fileType2: 0,
            showInfo: 2,
            refreshKey: 0,
            disabled: false,
            isShowEdit: true,
            uuid: "",
            cordId: "",
            isShow: false,
            isExamine: false,
            userId:null,
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 【请填写功能名称】表格数据
            recordsList: [],
            // 弹出层标题
            title: "",
            dialogVisible: false,
            dialogImageUrl: '',
            businessRecords: "businessRecords",
            businessAnnotations: "businessAnnotations",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 5,
                businessId: null,
                followTime: null,
                followId: null,
                followPerson: null,
                followStage: null,
                type: null,
                latestDevelopments: null,
                annotationsId: null,
                annotationsName: null,
                annotations: null,

            },
            strManagerDisplayArr:null,
            // 表单参数
            form: {

              // annotationName:"湖南众满特种轮胎科技有限公司, HT-003, 湘潭县中小企业公共服务平台"
            },
            selectedUserId: "",
            // 表单校验
            rules: {
                type: [
                    { required: true, message: "跟进方式不能为空", trigger: "change" },
                ],
                followStage: [
                    { required: true, message: "跟进阶段不能为空", trigger: "change" },
                ],
                latestDevelopments: [
                    { required: true, message: "最新进展不能为空", trigger: "blur" },
                    { max: 500, message: '最新进展长度不能超过500', trigger: 'blur' }
                ],
                annotations: [
                    { max: 500, message: '批注长度不能超过500', trigger: 'blur' }
                ],
                businessStatus:[
                    { required: true, message: '请选择审核状态', trigger: 'change' }
                ],
              strNickName: [
                    { required: true, message: '请选择审核人', trigger: 'change' }
                ]
            }
        };
    },
    created() {
        this.userName = this.$store.state.user.info.nickName;
        this.userId=this.$store.state.user.info.userId;
        console.log(this.userId,'this.userId')
        console.log(this.businessStatus,'this.businessStatus')
        this.getList();
    },

    watch: {
        obj(newVal) {
            this.queryParams.businessId = newVal.businessId;
            this.businessId = newVal.enterpriseId
            listRecords(this.queryParams).then(response => {
                this.recordsList = response.rows;
            });
        },
    },
  methods: {
        userShow(type) {
          this.strManagerDisplayArr=''
          if (type==6){
            this.userType = "1";
          }else {
            this.userType = "0";
          }
          this.show = type;
          this.$refs.select.show();
        },
        selectUser(userId,userName,deptIds,deptNames,nickName) {
          this.selectedUserId = userId;
          if(this.show=="2"){
            this.$set(this.form, "developmentId", userId);
            this.$set(this.form, "developmentManager", userName);
            this.$set(this.form, "developmentManagerNickName", nickName);
          }else if (this.show == "3") {
            this.$set(this.form, "transactionId", userId);
            this.$set(this.form, "businessManager", userName);
            this.$set(this.form, "businessManagerNickName", nickName);
          } else if (this.show == "4") {
            this.$set(this.form, "collaboratorId", userId);
            this.$set(this.form, "collaboratorName", userName);
            this.$set(this.form, "collaboratorNickName", nickName);
          }
          else if (this.show == "5") {
            this.$set(this.form, "arrayUserid", userId);
            this.$set(this.form, "annotationName", userName);
            this.$set(this.form, "annotationNickName", nickName);
          }
          else if (this.show == "6") {
            this.$set(this.form, "businessStatusUser", userId);
            this.$set(this.form, "strName", userName);
            this.$set(this.form, "strNickName", nickName);
          }
        },
        /** 查询【请填写功能名称】列表 */
        getList() {
            this.recordsList = [];
            this.queryParams.businessId = this.bId;
            listRecords(this.queryParams).then(response => {
                this.recordsList = response.rows;
                this.total = response.total;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        handlePictureCardPreview(url) {
            this.dialogImageUrl = url;
            this.dialogVisible = true;
        },
        getFile(data) {
            console.log(JSON.stringify(data))
        },
        // 表单重置
        reset() {
            this.form = {
                recordsId: null,
                businessId: null,
                followTime: null,
                followId: null,
                followPerson: null,
                followStage: null,
                type: null,
                latestDevelopments: null,
                annotationsId: null,
                annotationsName: null,
                annotations: null,
              followDateTime:null,
              strNickName:null,
              businessStatusUser:null,
              strName:null,
              businssStatus:null,
            };
            //this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.recordsId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        // handleAdd() {
        //     this.strManagerDisplayArr=""
        //     this.reset();
        //     this.uuid = this.guid();
        //     this.cordId = this.uuid;
        //     this.isExamine=false;
        //     this.isShow = false;
        //     this.disabled = false;
        //     this.form.followPerson = this.$store.state.user.info.nickName;
        //     this.form.followTime = this.showDate();
        //     this.form.businessId = this.bId;
        //     this.fileType = 0;
        //     this.fileType2 = 0;
        //    if (this.strNickName!=null && this.strNickName!=undefined && this.strNickName!=''){
        //      this.form.strNickName=this.strNickName;
        //    }else {
        //      getInformation(this.form.businessId).then(res=>{
        //        this.form.strNickName=res.data.strNickName
        //      })
        //    }
        //    getInformation(this.form.businessId).then(res => {
        //      this.businessStatus = res.data.businessStatus;
        //      this.open = true;
        //    })
        //     this.title = "新增跟进记录";
        //     this.refreshKey++;
        // },
        handleAdd() {
          this.strManagerDisplayArr = "";
          this.reset();
          this.uuid = this.guid();
          this.cordId = this.uuid;
          this.isExamine = false;
          this.isShow = false;
          this.disabled = false;
          this.form.followPerson = this.$store.state.user.info.nickName;
          this.form.followTime = this.showDate();
          this.form.businessId = this.bId;
          this.fileType = 0;
          this.fileType2 = 0;

          // 移除冗余的 getInformation 调用
          if (this.strNickName) {
            this.form.strNickName = this.strNickName;
          }
          // 合并 getInformation 的调用以减少不必要的网络请求
          getInformation(this.form.businessId).then(res => {
            this.form.strNickName = res.data.strNickName;
            this.businessStatus = res.data.businessStatus;
            this.open = true;
            this.title = "新增跟进记录";
            this.refreshKey++;
          }).catch(error => {
          });
        },

    formatterType(value) {
            var type = "";
            this.dict.type.enterprise_records.forEach(item => {
                if (item.value == value)
                    type = item.label;
            });
            return type;
        },
        formatterFollowStage(value) {
            var type = "";
            this.dict.type.tracking_stage.forEach(item => {
                if (item.value == value)
                    type = item.label;
            });
            return type;
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            this.fileType = 1;
            this.fileType2 = 1;
            this.disabled = false;
            this.isExamine=false;
            this.isShow=false;
            this.title = "修改跟进记录";
          const annotationsArray = row.annotationsUserId ? row.annotationsUserId.split(",") : [];
          console.log(annotationsArray,'annotationsArray')
          console.log(this.$store.state.user.info.userId,'this.$store.state.user.info.userId')
            const recordsId = row.recordsId || this.ids
            this.cordId = row.recordsId;
            getRecords(recordsId).then(response => {
                this.form = response.data;
                this.businessStatus = response.data.businessStatus;
                this.open = true;
                this.strManagerDisplayArr = response.data.sysUser.map(user => user.nickName).join(',');
                console.log(this.strManagerDisplayArr,'this.strManagerDisplayArr111');
            });
            this.refreshKey++;
        },
      handleAnnotations(row){
        this.reset();
        this.fileType = 1;
        this.fileType2 = 1;
          this.isShow = true;
          this.disabled = true;
          this.readonly= true;
        this.isExamine=false;
          this.title = "批注跟进记录";
        const recordsId = row.recordsId || this.ids
        this.cordId = row.recordsId;
        getRecords(recordsId).then(response => {
          this.form = response.data;
          this.open = true;
          this.strManagerDisplayArr = response.data.sysUser.map(user => user.nickName).join(',');
          console.log(this.strManagerDisplayArr,'this.strManagerDisplayArr111');
        });
        this.refreshKey++;
      },
      handleExamine(row){
        this.reset();
        this.fileType = 2;
        this.fileType2 = 1;
        this.disabled = true;
        this.isExamine=true;
        this.title = "审核跟进记录";
        const recordsId = row.recordsId || this.ids
        this.cordId = row.recordsId;
        getRecords(recordsId).then(response => {
          this.form = response.data;
          this.form.businessStatus = this.businessStatus;
          this.open = true;
          this.strManagerDisplayArr = response.data.sysUser.map(user => user.nickName).join(',');
        });
        this.refreshKey++;
      },
        /** 提交按钮 */
        submitForm() {
          console.log(this.form.arrayUserid,'this.form.arrayUserid');
          if (this.form.arrayUserid!==null&&this.form.arrayUserid!==undefined) {
            this.form.arrayUserid = this.form.arrayUserid.map(String)
          }
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.recordsId != null) {
                        updateRecords(this.form).then(response => {
                            this.refreshKey++;
                            if (this.form.annotations != null && this.form.annotations != "") {
                                this.$modal.msgSuccess("批注成功");
                            } else {
                                this.$modal.msgSuccess("修改成功");
                            }
                            this.open = false;
                            this.$emit('change');
                            this.getList();
                        });
                    } else {
                        this.form.recordsId = this.uuid;
                        addRecords(this.form).then(response => {
                            this.refreshKey++;
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                          getInformation(this.form.businessId).then(res => {
                            this.businessStatus=res.data.businessStatus;
                            this.$emit('change');
                            this.getList();
                          });
                        });
                    }
                }
            });
        },
      submitRemark(){
        if (this.form.arrayUserid!==null&&this.form.arrayUserid!==undefined) {
          this.form.arrayUserid = this.form.arrayUserid.map(String)
        }
        this.$refs["form"].validate(valid => {
          if (valid) {
            commentRecords(this.form).then(response => {
              this.refreshKey++;
              this.$modal.msgSuccess("批注成功");
              this.open = false;
              this.$emit('change');
              this.getList();
            });
          }
        });
      },
      examine(){
        if(this.form.businessStatus==null){
          this.$message.error('请选择审核意见')
        }else{
          updateInformation({businessId:this.form.businessId,businessStatus:this.form.businessStatus,recordsId:this.form.recordsId}).then(res => {
            this.$modal.msgSuccess("审核成功");
            getInformation(this.form.businessId).then(res=>{
              this.businessStatus=res.data.businessStatus;
              this.open = false;
              this.$emit('change');
              this.getList();
            })
          })
        }
      },
        /** 删除按钮操作 */
        handleDelete(row) {
            const recordsIds = row;
            this.$modal.confirm('是否确认删除该条跟进记录信息？').then(function () {
                return delRecords(recordsIds);
            }).then(() => {
                this.getList();
                this.$emit('change');
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },
        showDate() {
            var mydate = new Date();
            var str = "" + mydate.getFullYear() + "-";
            str += (mydate.getMonth() + 1) <= 9 ? "0" + (mydate.getMonth() + 1) + "-" : mydate.getMonth() + 1 + "-";
            str += mydate.getDate() <= 9 ? "0" + mydate.getDate() + " " : mydate.getDate() + " ";
            str += mydate.getHours() <= 9 ? "0" + mydate.getHours() + ":" : mydate.getHours() + ":";
            str += mydate.getMinutes() <= 9 ? "0" + mydate.getMinutes() + ":" : mydate.getMinutes() + ":";
            str += mydate.getSeconds() <= 9 ? "0" + mydate.getSeconds() : mydate.getSeconds();
            return str;
        },
        guid() {
            function S4() {
                return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
            }
            return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
        },
    },
    computed: {
      strManagerDisplay() {
        console.log(this.strManagerDisplayArr,'this.strManagerDisplayArr222');
        return this.strManagerDisplayArr||this.form.annotation || this.form.annotationNickName;
      },
      strExamineDisplay(){
        console.log(this.form.strNickName,'是否执行');
        return this.form.strNickName || this.form.strName;
      }
    },
};
</script>
<style scoped>
.el-descriptions-item__label {
    margin-left: 5px;
}

.el-descriptions__header {
    padding: 0px;
}

.el-descriptions-item__label.has-colon::after {
    content: "";
}
</style>
